public class Solution2 {
    //918. 环形子数组的最大和
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int[] f = new int[n+1]; //以i结尾的最大子数组和
        int[] g = new int[n+1]; //以i结尾的最小子数组和
        int fMax = Integer.MIN_VALUE;
        int gMin = Integer.MAX_VALUE;
        int sum = 0;
        for (int i = 1; i < n+1; i++) {
            f[i] = Math.max(f[i-1]+nums[i-1],nums[i-1]);
            g[i] = Math.min(g[i-1]+nums[i-1],nums[i-1]);
            fMax = Math.max(fMax,f[i]);
            gMin = Math.min(gMin,g[i]);
            sum += nums[i-1];
        }
        return sum == gMin ? fMax : Math.max(sum-gMin,fMax);
    }
}
